﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AsPlugInManager;
using AsLib;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.Globalization;

namespace NNLInterface
{
    public partial class frmExportPlan : NNLInterface.frmBaseBasic
    {

        #region 初始化

        private ASPSchedulingParameter aspparameter;
        string strSQLHead = " SELECT * FROM vie_oplog ol where  ol.DataType='Plan Export' ";
        string strTranNo = "";
        private System.Data.DataTable dt;

        public frmExportPlan()
        {
            InitializeComponent();
        }

        public frmExportPlan(IASPArgList argList)
        {
            InitializeComponent();
            common.agrs = (ASPArgList)argList;
            this.CmdImport.Caption = "导出";


        }

        private void frmExportPlan_Load(object sender, EventArgs e)
        {

            //如果当前工程下的用户名为空，则提示输入
            if (common._userid == "")
            {
                frmLogon frmLog = new frmLogon();
                frmLog.ShowDialog();

                if (frmLog.DialogResult == DialogResult.OK)
                {
                    frmLog.Dispose();
                    frmLog = null;
                }
                else
                {
                    this.Close();
                    return;
                }

            }

            IniDataSource();
        }

        private void IniDataSource()
        {
            //设定日期值
            this.dteFrom.EditValue = DateTime.Now;
            this.dteTo.EditValue = DateTime.Now.AddDays(common.sysParameter.IntervalDays);
            this.txtUser.Text = common._userid;
            this.txtUserName.Text = common._username;
            this.txtDeptNo.Text = common._DeptNo;
            this.txtDeptName.Text = common._DeptName;
            this.CmdImport.Caption = "发布";
            string strSQL = strSQLHead ;
            common.SubShowList(accessdb.GetRecord(strSQL).ADODataRst, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
            common.ReStoreLayOut(this.ListView);
            common.GetResourceString(this, this.ListView);
            common.RestoreFormLayOut(this, this.layOut, this.grpHead);
            this.SetToolVisible(common.ToolVisible.ImportData);
            this.logButtonVisibility = false;

        }
        #endregion

        private void frmExportPlan_FormClosing(object sender, FormClosingEventArgs e)
        {
            serial.SerializeBinary(common.sysParameter, Application.StartupPath + @"\NNLInterface.dat");
            common._its_accessdb = null;
            common.pro = null;
            GC.Collect();
        }

        private void frmExportPlan_ToolButtonClick(object sender, string e)
        {
            try
            {
                switch (e)
                {
                   
                    case "import":
                        if (!CheckData()) return;
                        subExportData();
                        break;
                    case "excel":
                        subExportXLS();
                        break;
                    case "print":
                        common.PrintView(this.ListGrid, "工单数据");
                        break;
                    case "exit":
                        common.SaveFormLayOut(this, this.layOut, this.grpHead);
                        common.SaveLayout(this.ListView);
                        this.Dispose();
                        break;
                    default:
                        {
                            break;
                        }
                }


            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        /// <summary>
        /// 检测日期范围是否已输入
        /// </summary>
        /// <returns></returns>
        private bool CheckData()
        {
            if(this.dteFrom.Text=="" )
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入一个正确的起始时间", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.dteFrom.Focus();
                return false;
            }

            if (this.dteTo.Text == "")
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入一个正确的截止时间", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.dteTo.Focus();
                return false;
            }


            return true;
        }


        private void subExportXLS()
        {
            try
            {
                if (!common.CheckExistsData(this.ListView)) return;
                common.ExportExcel(this.ListView);
                return;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        //导出计划
        private bool subExportData()
        {
            Cursor currentCursor = Cursor.Current;
            try
            {
                string strDelete = "";
                if (DevExpress.XtraEditors.XtraMessageBox.Show("确定要发布最新的计划吗(Y/N)?", common.sysParameter.MessageInf, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return false;
                Cursor.Current = Cursors.WaitCursor;

                //删除过期数据,最少15天
                //2012/01/30修改，将分别删除各个课所在的表的数据
                strDelete = "EXEC pro_DeleteData" + common._userid
                           + " " + common.sysParameter.DeleteDays.ToString();
                if (!accessdb.RsChange(strDelete)) return false;

                //从项目设定中取出前缀
                string strDepartNo = common.pro.GetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "ProjectUser_DepartNo")), 1);

                //取得最大的批次号
                strTranNo = Convert.ToString(accessdb.GetField("SELECT '" + strDepartNo + "' + replace(dbo.GetShortDate(GETDATE()),'-','')"));
                strTranNo = Convert.ToString(accessdb.ExecuteSP("pro_GetMaxNoteNo", common.Choose.HasAOutput, new object[] { strTranNo, 3, "ExportPlan", strTranNo }));


                //*********************此处注意有多个用户同时导出的情况，会出现冲突
                string strSQL = "";

                //导出品目,采用差分方式
                bool ExStatus = false;
                //只取出存在子对象的数据
                string strFilter = "FValid(ME.Child)";
                ExStatus = common.subExportAsprova("Item" + common._userid, "ItemExport", strFilter, TIsSaveTable.kIsSaveTableYes);

                if (!ExStatus)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("将品目导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DeleteErrorData();
                    return false;
                }

                //导出资源
                strFilter ="me.Res_Group!='模具'";
                ExStatus = common.subExportAsprova("Resource" + common._userid, "ResourceExport", strFilter, TIsSaveTable.kIsSaveTableYes);

                if (!ExStatus)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("将资源导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DeleteErrorData();
                    return false;
                }

                if (chkBOM.Checked)  //如果选择导入BOM
                {
                    //导出BOM
                    //2012-02-02采用全删全写的方式
                    strDelete = "TRUNCATE TABLE  Integrated" + common._userid;
                    if (!accessdb.RsChange(strDelete)) return false;

                    ExStatus = common.subExportAsprova("BOM" + common._userid, "IntegratedMasterExport", "", TIsSaveTable.kIsSaveTableYes);

                    if (!ExStatus)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("将制造BOM导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        DeleteErrorData();
                        return false;
                    }

                    //检查BOM的数据的正确性，此处去掉，改为直接取工作表中的自室外义字段，取制造的数量

                    //string sql = "SELECT iz.FinalItemCode,iz.ProcNo,iz.ProcCode \n"
                    //           + "FROM Integrated" + common._username + " iz WHERE iz.InstructionCode='In99' \n"
                    //           + "GROUP BY iz.FinalItemCode,iz.ProcNo,iz.ProcCode  \n"
                    //           + "HAVING COUNT(*)>1";
                    //DataTable dtCheck = accessdb.GetRecord(sql).ADODataRst;
                    //if(dtCheck.Rows.Count>=1)
                    //{
                    //    DevExpress.XtraEditors.XtraMessageBox.Show("BOM中存在同一工序存在2个以上的指令代码为In99的的输入指令,请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //    frmInformation frmCheckData = new frmInformation(dtCheck, "错误数据列表", "BomUseChk");
                    //    frmCheckData.ShowDialog();
                    //    frmCheckData = null;
                    //    DeleteErrorData();
                    //    return false;
                    //}
                }

                //导出出勤模式
                //ExStatus = common.subExportAsprova("ShiftOut", "ShiftOutExport", "", TIsSaveTable.kIsSaveTableYes);

                //if (!ExStatus)
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show("将出勤模式导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    DeleteErrorData();
                //    return false;
                //}

                //输入指令
                //删除临时表数据

                DateTime dteFromfilter = Convert.ToDateTime(this.dteFrom.Text);
                DateTime dteTofilter = Convert.ToDateTime(this.dteTo.Text);

                string dayStartTime = common.pro.DayStartTime.ToString("HH:mm:ss");

                string strFrom = dteFromfilter.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo) + " " + dayStartTime;
                string strTo = dteTofilter.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo) + " " + dayStartTime;

                strDelete = "TRUNCATE TABLE InputInstructionTmp" + common._userid;
                if (!accessdb.RsChange(strDelete)) return false;
                strFilter = "(ME.WorkInst_Operation.Work_IsAssigned=='1'||ME.WorkInst_Operation.Work_IsAssigned=='3')  && ( !(ME.WorkInst_Operation.Work_StartTime>#" + strTo + "# || ME.WorkInst_Operation.Work_EndTime<#" + strFrom + "#))";
                ExStatus = common.subExportAsprova("InputWorkInstruction" + common._userid, "InputWorkInstructionExport", strFilter, TIsSaveTable.kIsSaveTableYes);

                if (!ExStatus)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("将输入指令导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DeleteErrorData();
                    return false;
                }
                else
                {
                    strSQL = "UPDATE i SET i.TranNo ='" + strTranNo + "',i.EntUser ='" + this.txtUser.Text + "' ,i.EntDate = GETDATE() FROM InputInstructionTmp" 
                            +  common._userid + " i "
                            + " WHERE ISNULL(i.TranNo,'')='' \r\n";

                    //写入数据
                    strSQL += "INSERT INTO InputInstruction" + common._userid + "  SELECT * FROM  InputInstructionTmp" + common._userid + " \r\n";
                }

                //输出指令
                //删除临时表数据
                //strDelete = "delete from  OutputInstructionTmp";
                //if (!accessdb.RsChange(strDelete)) return false;

                //ExStatus = common.subExportAsprova("OutputInstruction", "OutputInstructionExport", "", TIsSaveTable.kIsSaveTableYes);

                //if (!ExStatus)
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show("将输出指令导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    DeleteErrorData();
                //    return false;
                //}
                //else
                //{
                //    strSQL += "UPDATE i SET i.TranNo ='" + strTranNo + "',i.EntUser ='" + this.txtUser.Text + "' ,i.EntDate = GETDATE() FROM OutputInstructionTmp i "
                //           + " WHERE ISNULL(i.TranNo,'')='' \r\n";
                //    //写入数据
                //    strSQL += "INSERT INTO OutputInstruction SELECT * FROM  OutputInstructionTmp \r\n";

                //}

                //使用指令
                //删除临时表数据
                strDelete = "TRUNCATE TABLE  UseInstructionTmp" + common._userid;
                if (!accessdb.RsChange(strDelete)) return false;

                //strFilter = "(ME.UseInst_UseBomInst=='M') &&   (ME.WorkInst_Operation.Work_IsAssigned=='1'||ME.WorkInst_Operation.Work_IsAssigned=='3')  && (!(ME.WorkInst_Operation.Work_StartTime>#" + strTo + "# || ME.WorkInst_Operation.Work_EndTime<#" + strFrom + "#))";
                strFilter = "(ME.WorkInst_Operation.Work_IsAssigned=='1'||ME.WorkInst_Operation.Work_IsAssigned=='3')  && (!(ME.WorkInst_Operation.Work_StartTime>#" + strTo + "# || ME.WorkInst_Operation.Work_EndTime<#" + strFrom + "#))";

                ExStatus = common.subExportAsprova("UseInstruction" + common._userid, "UseInstructionExport", strFilter, TIsSaveTable.kIsSaveTableYes);

                if (!ExStatus)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("将使用指令导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DeleteErrorData();
                    return false;
                }
                else
                {
                    if(!CheckUseInstructionData())
                    {
                        DeleteErrorData();
                        return false;
                    }
                    
                    strSQL += "UPDATE i SET i.TranNo ='" + strTranNo + "',i.EntUser ='" + this.txtUser.Text + "' ,i.EntDate = GETDATE() FROM UseInstructionTmp" + common._userid + " i "
                           + " WHERE ISNULL(i.TranNo,'')='' \r\n";
                    //写入数据
                    strSQL += "INSERT INTO UseInstruction" + common._userid + "  SELECT * FROM  UseInstructionTmp" + common._userid + " \r\n";


                }

                //导出订单
                strDelete = "TRUNCATE TABLE  OrdersOutTmp" + common._userid;
                if (!accessdb.RsChange(strDelete)) return false;

                //只导出已分派的订单
                ExStatus = common.subExportAsprova("Orders" + common._userid, "OrdersExport", "", TIsSaveTable.kIsSaveTableYes);

                if (!ExStatus)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("将订单导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DeleteErrorData();
                    return false;
                }
                else
                {
                    strSQL += "UPDATE i SET i.TranNo ='" + strTranNo + "',i.EntUser ='" + this.txtUser.Text + "' ,i.EntDate = GETDATE() FROM OrdersOutTmp" + common._userid + " i "
                           + " WHERE ISNULL(i.TranNo,'')='' \r\n";
                    //写入数据
                    strSQL += "INSERT INTO OrdersOut" + common._userid + " SELECT * FROM  OrdersOutTmp" + common._userid + " \r\n";

                }

                ////导出生产计划
                //产生导出过滤条件
                strDelete = "TRUNCATE TABLE  OperationTmp" + common._userid;
                if (!accessdb.RsChange(strDelete)) return false;

                strFilter = "(!(ME.Work_StartTime>#" + strTo + "# || ME.Work_EndTime<#" + strFrom + "#)) && (ME.Work_IsAssigned=='1' ||  ME.Work_IsAssigned=='3') && ME.Type!='S'";
                ExStatus = common.subExportAsprova("Operation"+ common._userid, "OperationExport", strFilter, TIsSaveTable.kIsSaveTableYes);

                if (!ExStatus)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("将生产计划导出时产生错误!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DeleteErrorData();
                    return false;
                }
                else
                {
                    strSQL += "UPDATE i SET i.TranNo ='" + strTranNo + "',i.EntUser ='" + this.txtUser.Text + "' ,i.EntDate = GETDATE() FROM Operationtmp" 
                            + common._userid + " i "
                            + " WHERE ISNULL(i.TranNo,'')=''";
                    //写入数据
                    strSQL += "INSERT INTO Operation" +common._userid + " SELECT * FROM  OperationTmp" + common._userid + " \r\n";

                }

                //删除多余的订单及使用指令数据
                strSQL += "DELETE FROM OrdersOut" + common._userid + " WHERE Code NOT IN (SELECT DISTINCT o.OrderCode "
                      + " FROM Operation" + common._userid + " o WHERE TranNo='" + strTranNo + "' ) "
                      + " AND tranno='" + strTranNo + "'\r\n";

                //更新工作的的时间序列
                //strSQL += "EXEC pro_UpdateTimeArray '" + strTranNo + "'\r\n";

                //更新各产品各工序所用到的模具，取BOM表中指令代码以'S'开头的副资源数据(在资源表中的资源组为模具的数据)

                strSQL += " EXEC pro_UpdateProModelNo" + common._userid +   " '" + strTranNo + "'\r\n";


                //解锁用户
                //strSQL += " UPDATE sps SET sps.OperationProcess = 0 FROM SysProSwitch sps "
                //             + " WHERE sps.ProcessType='PlanExport'  ";


                //写入更新标志,已导入Asprova标志及日志
                strSQL += " insert into OpLog values('" + strTranNo
                                + "','Plan Export',1"
                                + ",'','','"
                                + common._userid
                                + "',getdate(),1) ";



                if (!accessdb.RsChange(strSQL)) return false;

                //2014-03-27以下为生成按天的计划数据，以便生成计划报表时直接生成数据
                if (!GetReportData()) return false;

                //2014-03-28为生成计划报表，需要将订单相关的信息导出至表[OrderOutPlan]中
                aspparameter = (AsLib.ASPSchedulingParameter)common.pro.RootCommandObject.FindChild("Scheduling").FindChild("ExportPlanData");
                common.pro.RescheduleByParameterName(aspparameter.Code, true);
                common.pro.BroadcastChanges();
                aspparameter = null;



                strSQL = strSQLHead;
                common.SubShowList(accessdb.GetRecord(strSQL).ADODataRst, this.ListGrid, this.ListView, false);
                common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
                common.ReStoreLayOut(this.ListView);


                DevExpress.XtraEditors.XtraMessageBox.Show("计划已成功发布!\r\n"
                                                           + "操作者:" + common._userid + "(" + common._username + ")\r\n"
                                                           + "导出版本号:" + strTranNo,
                                                           common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return true;
            }
            catch(Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //UnlockUser();

                return false;
            }
            finally
            {
                //UnlockUser();
                Cursor.Current = currentCursor;


            }
           
        }

        private bool GetReportData()
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                //根据版本号生成数据，如果已经生成，则不需要重复生成
                string itemID = Convert.ToString(accessdb.GetField("SELECT CONVERT(VARCHAR(300),GETDATE(),121)"));


                //设定版本号
                string strSQL = string.Format("SELECT  max(o.TranNo) FROM OperationZ1 o ");
                string strTranNo = accessdb.GetField(strSQL).ToString();

                string strUpDate = " SET XACT_ABORT ON  BEGIN TRAN \r\n";
                strSQL = "SELECT COUNT(*) FROM ScheduleZ1D od WHERE od.TranNo='" + strTranNo + "'";
                DataTable OperationDays;

                if (Convert.ToInt32(accessdb.GetField(strSQL)) < 1)
                {

                    strSQL = "SELECT * FROM vie_OperationDetailZ1 vod WHERE vod.TranNo='" + strTranNo + "'";
                    DataTable dt = accessdb.GetRecord(strSQL).ADODataRst;


                    //生成每天的工作计划
                    for (int i = 0; i < dt.Rows.Count; i++)   //对应每一个工作
                    {
                        string TimeArray = dt.Rows[i]["TimeArray"].ToString();
                        string OperationNo = dt.Rows[i]["Code"].ToString();
                        string TranNo = dt.Rows[i]["TranNo"].ToString();
                        string TaskType = dt.Rows[i]["TaskType"].ToString();

                        //先找出当前工作所对应的工作日
                        OperationDays = GetOperationDays(TimeArray);



                        for (int j = 1; j <= OperationDays.Rows.Count; j += 2)
                        {
                            //写入每个工作所对应的所有时序,可能存在跨天的情况，需要在显示报表时，对时间段进行分割
                            strUpDate += " INSERT INTO OperationDetailTmpZ1 " 
                            + "(Code,TranNo,StartTime,EndTime,TaskType,ItemID) VALUES('"
                            + OperationNo + "','"
                            + TranNo + "','"
                            + OperationDays.Rows[j - 1][0].ToString() + "','"
                            + OperationDays.Rows[j][0].ToString() + "','"
                            + TaskType + "','"
                            + itemID + "') \r\n";

                        }

                    }


                    //如果是多芯的数据，则需要将前设置时间变为一芯的设定时间，将制造时间提前处理
                    strUpDate += " EXEC pro_UpdateOperationSeupTimeZ1 '" + strTranNo + "'\r\n";


                    //取得当前的临界时间
                    string dayStartTime = common.pro.DayStartTime.ToString("HH:mm:ss");

                    //分隔时间段
                    strUpDate += " EXEC pro_SplictTimesZ1 " 
                                + " @ItemID ='" + itemID
                                + "', @DaySplict ='" + dayStartTime
                                + "',@EntUser ='Z1'\n";

                    //2012-02-21根据要生成的数据
                    strUpDate += " EXEC pro_CreatePlanDataZ1" 
                                + "  @tranNo ='" + strTranNo + "'";
                    strUpDate += " commit tran ";
                    accessdb.RsChange(strUpDate);

                }

                return true;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return false;
            }
            finally
            {
                Cursor.Current = currentCursor;
            }
        }


        //找出工作对应的工作日
        private DataTable GetOperationDays(string strTimeArray)
        {
            string[] strTimes;

            DataTable dt = new DataTable("dataTmp");
            dt.Columns.Add("day", typeof(string));

            strTimes = strTimeArray.Split(';');
            for (int i = 0; i < strTimes.Length; i++)
            {
                dt.Rows.Add(new object[] { strTimes[i].ToString() });

            }



            return dt;
        }

        private bool CheckUseInstructionData()
        {
            //检查输入指令是否正确
            //检查指令中每个工序中的codetype=M
            string strSQL = "SELECT aa.OperationNo \n"
           + "  FROM (SELECT DISTINCT  uiz.OperationNo FROM UseInstructionTmp" + common._userid + " uiz  ) aa \n"
           + "LEFT OUTER JOIN  (SELECT uiz.CodeType,uiz.OperationNo \n"
           + "                    FROM UseInstructionTmp" + common._userid + " uiz WHERE   uiz.CodeType='M' ) bb  \n"
           + "ON aa.OperationNo=bb.OperationNo \n"
           + "WHERE bb.CodeType IS null";
            DataTable dataCheck = accessdb.GetRecord(strSQL).ADODataRst;
            if (dataCheck.Rows.Count >= 1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("存在工作使用指令中代码为全不为M的数据,请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                frmInformation frmCheckData = new frmInformation(dataCheck, "错误数据列表", "ExportUseChk");
                frmCheckData.ShowDialog();
                frmCheckData = null;
                return false;
            }

            //检查相同的工作，相同的工序是否存在两个以上的代码为M的数据
           strSQL = "SELECT uitz.OperationNo,uitz.TaskType FROM UseInstructionTmp" + common._userid + " uitz \n"
                   + "WHERE uitz.CodeType='M'  \n"
                   + "GROUP BY  OperationNo,uitz.TaskType \n"
                   + "HAVING COUNT(*)>1";
           dataCheck = accessdb.GetRecord(strSQL).ADODataRst;
           if (dataCheck.Rows.Count >= 1)
           {
               DevExpress.XtraEditors.XtraMessageBox.Show("工作使用指令中存在代码为M的重复数据，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
               frmInformation frmCheckData = new frmInformation(dataCheck, "错误数据列表", "ExportUseChk");
               frmCheckData.ShowDialog();
               frmCheckData = null;
               return false;
           }
           return true;
        }

        private void UnlockUser()
        {
            //解锁用户
            string strSQL = " UPDATE sps SET sps.OperationProcess = 0 FROM SysProSwitch sps "
                         + " WHERE sps.ProcessType='PlanExport'  ";
            accessdb.RsChange(strSQL);
        }



        //如果导出失败，则删除之前导入的数据
        private void DeleteErrorData()
        {
            string strSQL = " SET XACT_ABORT ON BEGIN TRAN "
                         + " DELETE FROM InputInstruction" + common._userid + " WHERE TranNo IS NULL "
                         + " DELETE FROM UseInstruction" + common._userid + " WHERE TranNo IS NULL "
                         + " DELETE FROM OrdersOut" + common._userid + " WHERE TranNo IS NULL "
                         + " DELETE FROM Operation" + common._userid + " WHERE TranNo IS null "
                         + " DELETE FROM OperationDetail" + common._userid + " WHERE TranNo IS null "
                         + " commit tran ";

            //将正在导入的状态置为0
            accessdb.RsChange(strSQL);
        }


        //切换用户
        private void txtChange_Click(object sender, EventArgs e)
        {
            frmLogon frmLog = new frmLogon();
            frmLog.ShowDialog();

            if (frmLog.DialogResult == DialogResult.OK)
            {
                IniDataSource();
            }

            frmLog.Dispose();
            frmLog = null;

        }
    }
}
